package server

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"smartHomeNode/v1/base"
	"strings"
	"time"
)

type Cron struct {
	Base
}

/**
 * 启动服务
 */
func (ctx *Base) CronServer() {
	fmt.Println("Starting cron server ...")

	c := cron.New()      // 创建定时任务 分钟
	cSpec := "* * * * *" // 每一分钟
	c.AddFunc(cSpec, func() {
		ctx.runTime()
	})
	c.Start()

	t := cron.New()
	tSpec := "6 6 * * *" // 每天6点执行
	t.AddFunc(tSpec, func() {
		ctx.recordTemp()
		ctx.recordHum()
	})
	t.Start()

	select {}
}

/**
 * 检查当前时间需要执行的任务
 */
func (ctx *Base) runTime() {
	weekDay := int(time.Now().Weekday())
	filePath := WEEKFILE + fmt.Sprintf("%v", weekDay)
	if ctx.CheckDir(filePath) {
		for _, fileList := range ctx.GetFileList(filePath) {
			path := filePath + "/" + fileList.Name()
			fileInfo := ctx.ReadFile(path)
			checkInfo := strings.Split(fileInfo, "#")
			if len(checkInfo) == 2 {
				nowTime := ctx.NowTime()
				if (nowTime[0] + ":" + nowTime[1]) == checkInfo[0] {
					arr := strings.Split(checkInfo[1], ",")
					if len(arr) > 0 {
						for _, code := range arr {
							fmt.Println("Cron call: " + code)
							ctx.RequestTCP(code)
						}
					}
				}
			} else {
				fmt.Println("Cron server data error")
			}
		}
	} else {
		ctx.CreateDir(filePath)
	}
}

/**
 * 记录温度信息
 */
func (ctx *Base) recordTemp() {
	dataList := base.TempData.Items()
	if len(dataList) > 0 {
		for deviceName, _ := range dataList {
			data, found := base.TempData.Get(deviceName)
			if found {
				info := strings.Split(fmt.Sprintf("%v", data), "&")
				filePath := SENSORSFILE + "Temp/" + deviceName + "/"
				ctx.InitDir(filePath)
				ctx.WriteFile(filePath+fmt.Sprintf("%v", int(time.Now().Weekday())), info[0])
			}
		}
	}
}

/**
 * 记录湿度信息
 */
func (ctx *Base) recordHum() {
	dataList := base.HumData.Items()
	if len(dataList) > 0 {
		for deviceName, _ := range dataList {
			data, found := base.HumData.Get(deviceName)
			if found {
				info := strings.Split(fmt.Sprintf("%v", data), "&")
				filePath := SENSORSFILE + "Hum/" + deviceName + "/"
				ctx.InitDir(filePath)
				ctx.WriteFile(filePath+fmt.Sprintf("%v", int(time.Now().Weekday())), info[0])
			}
		}
	}
}
